# -*- coding: utf8 -*-

import os

def which(bin_exe):
    # support Linux / POSIX here?
    paths = ["/bin", "/sbin", "/usr/bin", "/usr/sbin", "/usr/local/bin", "/usr/local/sbin"]
    if "PATH" in os.environ:
        paths = os.environ["PATH"].split(":")
    for p in paths:
        full_path = os.path.join(p, bin_exe)
        if os.path.isfile(full_path) and os.access(full_path, os.X_OK):
            return full_path
    return bin_exe

support_mime = {
    "p7zip" : ("application/zip", "application/x-rar", "application/x-7z-compressed"),
    "tar" : ("application/x-tar"),
    "pdf" : ("application/pdf")
}

def is_supported( file_mime ):
    for ad, mimes in list(support_mime.items()):
        for mime in mimes:
            if file_mime == mime:
                return True
    return False



class Archive(object):
    
    file_name = None
    mime = None
    _adapter = None

    def __init__(self, file_name, mime):
        self.file_name = file_name
        self.mime = mime
        return

    def get_adapter( self ):
        """
        @return Archive Adapter Object
        @rtype BaseAdapter
        """
        if not self._adapter:
            self._adapter = BaseAdapter(self.file_name)
            if self.mime in support_mime["p7zip"]:
                from archive.p7zip import P7ZipArchive
                self._adapter = P7ZipArchive(self.file_name)
            if self.mime in support_mime["tar"]:
                from archive.tar import TarArchive
                self._adapter =  TarArchive(self.file_name)
            if self.mime in support_mime["pdf"]:
                from archive.pdf import PDFArchive
                self._adapter =  PDFArchive(self.file_name)
        return self._adapter
    
    def get_files( self ):
        return self.get_adapter().get_files()
        
    def extract_file( self, name, into_dir ):
        return self.get_adapter().extract_file( name, into_dir )

    def extract_files( self, into_dir ):
        return self.get_adapter().extract_files( into_dir )

    def remove_file( self, name ):
        return self.get_adapter().remove_file( name )
        
    pass


class BaseAdapter(object):

    bin = None
    file_name = None

    def __init__(self, file_name):
        self.file_name = file_name
        return

    def get_files( self ):
        """
        @return List of file names
        @rtype list
        """
        raise NotImplemented

    def extract_file( self, name, into_dir ):
        raise NotImplemented

    def extract_files( self, into_dir ):
        raise NotImplemented

    def remove_file( self, name ):
        raise NotImplemented

    pass
